#define JMBC_INSIDE
#include "slVORBIS.h"
#include "slSound.h"
#include <Core/clCore.h>
#include <vorbis/vorbisfile.h>
#include <stdio.h>
#include <stdlib.h>

void
slSoundLoadVORBIS(unsigned int id, unsigned int filepath)
{
	FILE *stream;
	char tmp[256];

	//stream = _wfopen(tlStringData(filepath), L"rb");
	wcstombs(tmp, tlStringData(filepath), 256);
	stream = fopen(tmp, "rb");

	if(stream)
	{
		OggVorbis_File ogg;

		if(ov_open(stream, &ogg, NULL, 0) == 0)
		{
			SLSound *sound;
			int bitstream;
			unsigned int read, nbytes, bytes, cbytes;
			char *samples;
			vorbis_info *vorbis;

			sound = slSoundStore(id);

			vorbis = ov_info(&ogg, -1);

			sound->rate = vorbis->rate;
			sound->channels = vorbis->channels;
			sound->frames = (unsigned int) ov_pcm_total(&ogg, -1);
			nbytes = sound->frames * sound->channels * sizeof(short);
			sound->samples = malloc(nbytes);

			read = 0;
			do
			{
				samples = (char *) sound->samples + read;
				cbytes = nbytes - read;
				bytes = ov_read(&ogg, samples, cbytes, 0, 2, 1, &bitstream);
				read += bytes;
			}	
			while(read < nbytes && bytes > 0);

			ov_clear(&ogg);
		}
		else
		{
			elErrorSet(EL_ERROR_INVALID);
			fclose(stream);
		}
	}
	else
		elErrorSet(EL_ERROR_INVALID);
}
